<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="产地" prop="factoryId">
        <el-select v-model="queryParams.factoryId" placeholder="请选择" filterable clearable @change="factoryChange">
          <el-option v-for="team in factoryList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择" clearable>
          <el-option v-for="team in teamList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="年月" prop="plan_months">
        <el-date-picker clearable
                        v-model="queryParams.plan_months"
                        type="months"
                        value-format="yyyy-MM"
                        placeholder="选择排产月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="合同号" prop="contractCode">
        <el-input v-model="queryParams.contractCode" placeholder="请输入合同号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading"
              show-summary
              border style="width:100%;" ref="multipleTable"
              :data="newOrderPlanList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"  :selectable="handleDisable"/>
      <el-table-column label="产品编码" align="center" prop="bomCode" width="120"/>
      <el-table-column label="产品名称" align="center" prop="bomName" width="180"/>
      <el-table-column label="班组名称" align="center" prop="teamName" width="110"/>
      <el-table-column label="合同编号" align="center" prop="contractCode"  width="150"/>
      <el-table-column label="订单日期" align="center" prop="orderDate" width="100" />
      <!--<el-table-column label="要求完成日期" align="center" prop="order_finishdate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.order_finishdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="排产年月周" align="center" prop="monthWeek"  width="100"/>-->
      <el-table-column label="排产开始日期" align="center" prop="planStartdate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planStartdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排产完成日期" align="center" prop="planFinishdate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planFinishdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单预计交期" align="center" prop="orderPlanFinishdate"  width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderPlanFinishdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产状态" align="center" prop="workerOrderstatusDesc" width="80" />
      <!--<el-table-column label="产地" align="center" prop="factoryName" width="120" :show-overflow-tooltip="true" />-->
     
      <el-table-column label="规格型号" align="center" prop="productStandard" :show-overflow-tooltip="true"/>
      <el-table-column label="产品单位" align="center" prop="productUnit"  width="80"/>
      <!--<el-table-column label="产品数量" align="center" prop="workerOrdernum"  width="80"/>
      <el-table-column label="采样数量" align="center" prop="sampleNum" />-->
      <el-table-column label="排产数量" align="center" prop="planNum" width="80"/>
      
      <!--<el-table-column label="是否缺料" align="center" prop="missingMaterail" width="80"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button-group>
            <el-button
              size="small"
              type="primary"
              @click="handlePlan(scope.row)"
            >调整排产</el-button
            >
          </el-button-group>
          <!--<el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.wplanStatus == '1'"
            @click="handlePrint(scope.row)" v-hasPermi="['factory:factorywplan:edit']">打印工单</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 排产调整对话框 -->
    <el-dialog title="产品排产调整" :visible.sync="open" width="1650px" :close-on-click-modal ="false" append-to-body>
      <!-- 数据统计 -->
      <div style="clear: both;margin-bottom: 30px;">
        <el-row :gutter="26">
          <el-col :span="3">
            <div>
              <el-statistic title="所选班组">
                <template slot="formatter">{{ teamName }}</template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic title="已选数量">
                <template slot="formatter">{{selectedCount}}条</template>
              </el-statistic>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="standardCapacity" title="标准产能/天"/>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="totalStandardCapacity" title="总标准产能" />
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="restCapacity" title="总剩余产能"/>
            </div>
          </el-col>
          <el-col :span="3">
            <div>
              <el-statistic group-separator="," :precision="2" :value="needCapacity" title="所需产能"/>
            </div>
          </el-col>
        </el-row>
      </div>
      <template v-for="planItem in wplanProductVOList">
        <div style="margin-right: 5px;margin-top: 10px;">
          <!--<el-tag :type="planItem.typeTag" size="medium"  effect="light" style="margin-right: 25px;">
            合同号：{{planItem.contractCode}} | 产品编码：{{planItem.productCode}} | 产品名称：{{planItem.productName}}
          </el-tag>-->
          <el-descriptions class="margin-top" title="" :column="3" size="small" border>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-check"></i>
                合同号
              </template>
              {{planItem.contractCode}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-order"></i>
                产品编码|产品名称
              </template>
              <el-tag type="danger">{{planItem.productCode}} | {{planItem.productName}}</el-tag>
            </el-descriptions-item>
            <!--<el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-order"></i>
                标签或包装选择
              </template>
              <el-checkbox v-model="planItem.labelCheckAll" @change="labelCheckAllChange(planItem)">标签文档全选</el-checkbox>
              <el-checkbox v-model="planItem.packageCheckAll" @change="packageCheckAllChange(planItem)">包装单全选</el-checkbox>
              <el-checkbox v-model="planItem.bothOfCheckAll" @change="bothOfCheckAllChange(planItem)">两者同时全选</el-checkbox>
            </el-descriptions-item>-->
          </el-descriptions>
        </div>
        <el-table
          style="width: 100%"
          row-key="id"
          show-summary
          border
          lazy
          v-loading="loading2"
          :load="load"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :data="planItem.wplanList" >
          <el-table-column label="子项物料编码" align="center" prop="bomCode"  width="160px" />
          <el-table-column label="物料名称" align="center" prop="bomName" />
          <el-table-column label="规格型号" align="center" prop="productStandard" />
          <el-table-column label="订单合同号" align="center" prop="contractCode" />
          <el-table-column label="订单日期" align="center" prop="orderDate">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!--<el-table-column label="标签文档" align="center" class-name="small-padding fixed-width" prop="labelCheck" width="60px">
            <template slot-scope="scope">
              <el-checkbox v-if="scope.row.levelValue===1" v-model="scope.row.labelCheck"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="包装单" align="center" class-name="small-padding fixed-width" prop="packageCheck" width="60px">
            <template slot-scope="scope">
              <el-checkbox v-if="scope.row.levelValue===1" v-model="scope.row.packageCheck"></el-checkbox>
            </template>
          </el-table-column>-->
          <el-table-column label="订单数量" align="center" prop="orderNum" />
          <el-table-column label="分单数量" align="center" prop="workerOrdernum" width="90px"/>
          <el-table-column label="采样数量" align="center" prop="sampleNum" width="80px"/>
          <el-table-column label="库存" align="center" prop="storeNum" width="90px"/>
<!--          <el-table-column label="待排产数量" align="center" prop="planNum" width="90px"/>-->
          <el-table-column label="已排产数量" align="center" prop="planCapacity"  width="110px">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.planNum!=null">{{scope.row.planNum}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="排产情况" align="center" prop="capacityDesc" width="100px"/>
          <el-table-column label="排产开始时间" align="center" prop="planStartDate"  width="100px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.planStartDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排产结束时间" align="center" prop="planEndDate"  width="100px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.planEndDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否缺料" align="center" prop="missingMaterial" />

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80px" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleAdjust(scope.row)"
              >调整排期</el-button>
              <!--<el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.levelValue===1"
                v-hasPermi="['order:plan:adjust']"
                @click="handPlanRemoveOrder(scope.row)"
              >移除</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="submitPlan" >保存调整</el-button>
      </div>
    </el-dialog>

    <!-- 排产调整对话框 -->
    <el-dialog
      title="排产调整"
      :visible.sync="adjustopen"
      width="800px"
      append-to-body
    >
      <el-form ref="form2" :model="form2" :rules="rules" label-width="120px">
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="旧的完成时间" prop="planEndDate1">
              <el-date-picker
                v-model="form2.planEndDate1"
                type="date"
                value-format="yyyy-MM-dd"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新预计完成时间" prop="planEndDate">
              <el-date-picker
                clearable
                v-model="form2.planEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择排产时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { newAdjustList,doneGroupList,submitAdjustNewPlan, adjustNewPlan  } from "@/api/sm/order/orderplan";
import { newplanCancel  } from "@/api/sm/order/orderinfo";
import { listTeam,listFactory } from "@/api/system/dept";
import { listChildren } from "@/api/sm/basic/bominfo";
import moment from "moment";

export default {
  name: "Orderinfo",
  dicts: ['order_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loading2: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      teamSelect: true,
      planCal: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      plantotal: 0,
      newOrderPlanList: [],
      factoryList: [],
      teamList: [],
      // 选中的调整工单-半成品吧
      adjustPlan: {},
      adjustWplanSelected: {},
      //排产工单
      wplanProductVOList: [],
      //排产结果
      planResultList: [],
      planStatusList: [
        {
          "label": "待排产",
          "value": 0
        },
        {
          "label": "排产完成",
          "value": 1
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      adjustopen: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bomCode: null,
        bomName: null,
        teamId: null,
        orderCode: null,
        contractCode: null,
        excludeIds: [],
        plan_months: null,
        plan_month: null,
      },
      // 表单参数
      form: {
        teamId: null,
        weekStartDate: null,
        weekEndDate: null,
        workOrderIds: null
      },
      // 表单参数
      form1: {
        wplanList: null
      },
      form2: { // 表单参数 - 调整计算的参数
        mId: null,
        bomCode: null,
        planStartDate: null,
        planEndDate: null,
        planStartDate1: null, // 原来的开始日期
        planEndDate1: null, // 原来的结束日期
      },
      // 表单参数 - 调整接收回来的参数
      form3: {
        factoryId: null,
        teamId: null,
        bomCode: null,
        planStartDate: null,
        planEndDate: null,
        adjustStartDate: null,
        adjustEndDate: null,
        detailList: []
      },
      // 表单校验
      rules: {
      },
      // 统计数据
      teamName: "-",
      selectedCount: 0,
      standardCapacity: 0,
      totalStandardCapacity: 0,
      restCapacity: 0,
      needCapacity: 0,
      action: null,
    };
  },
  created() {
    this.init();
    this.getFactoryList();
    // this.getList();
  },
  methods: {
    init() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 月份需要加1，然后确保是两位数
      const day = currentDate.getDate().toString().padStart(2, '0'); // 获取日并确保是两位数
      this.queryParams.plan_months = `${year}-${month}`;
    },
    formatDateToYYYYMMDD(date) {
      if (date) {
        return moment(date).format('YYYY-MM-DD');
      }
      return "";
    },
    wplanDateRemove(row) {
      let wplanList = this.adjustWplanSelected.detailList;
      if (wplanList.length === 0) {
        alert('已经无日期删除');
      }
      for(let i=0;i<wplanList.length;i++) {
        let obj = wplanList[i];
        if (obj.planDate === row.planDate) {
          wplanList.splice(i, 1);
          break;
        }
      }
    },
    wplanDateChange() {
      let detailList = this.adjustWplanSelected.detailList;
      if (detailList.length === 0) {
        alert('已经无日期调整');
      }
      let cloneSrcObject = this.adjustWplanSelected.detailList[0];

      const newStart = new Date(this.adjustWplanSelected.planStartDate);
      const newEnd = new Date(this.adjustWplanSelected.planEndDate);

      let preStart = new Date(this.adjustWplanSelected.detailList[0].planDate);
      let preEnd = new Date(this.adjustWplanSelected.detailList[this.adjustWplanSelected.detailList.length-1].planDate);

      // 调整结束日期，循环变量从起始日期开始，逐天增加
      while (newEnd > preEnd) {
        preEnd.setDate(preEnd.getDate() +1);
        let curPlanDate = this.formatDateToYYYYMMDD(preEnd);
        const exists = this.adjustWplanSelected.detailList.some(item => item.planDate === curPlanDate);
        if (!exists) {
          let rowWPlan = {};
          Object.assign(rowWPlan, cloneSrcObject);
          rowWPlan.planCapacity = 0;
          rowWPlan.planDate = curPlanDate;
          this.adjustWplanSelected.detailList.push(rowWPlan);
        }
      }

      // 调整开始日期
      while (newStart < preStart) {
        preStart.setDate(preStart.getDate() -1);
        let curPlanDate = this.formatDateToYYYYMMDD(preStart);
        const exists = this.adjustWplanSelected.detailList.some(item => item.planDate === curPlanDate);
        if (!exists) {
          let rowWPlan = {};
          Object.assign(rowWPlan, cloneSrcObject);
          rowWPlan.planCapacity = 0;
          rowWPlan.planDate = curPlanDate;
          this.adjustWplanSelected.detailList.unshift(rowWPlan);
        }
      }
    },
    labelCheckAllChange(planItem) {
      let wplanList = planItem.wplanList || [];
      for(let wplan of wplanList) {
        wplan.labelCheck = planItem.labelCheckAll;
      }
      planItem.bothOfCheckAll = planItem.labelCheckAll && planItem.packageCheckAll;
    },
    packageCheckAllChange(planItem) {
      let wplanList = planItem.wplanList || [];
      for(let wplan of wplanList) {
        wplan.packageCheck = planItem.packageCheckAll;
      }
      planItem.bothOfCheckAll = planItem.labelCheckAll && planItem.packageCheckAll;
    },
    bothOfCheckAllChange(planItem) {
      let wplanList = planItem.wplanList || [];
      for(let wplan of wplanList) {
        wplan.labelCheck = planItem.bothOfCheckAll;
        wplan.packageCheck = planItem.bothOfCheckAll;
      }
      planItem.labelCheckAll = planItem.bothOfCheckAll;
      planItem.packageCheckAll = planItem.bothOfCheckAll;
    },

    /** 调整排产日期功能 提交按钮 */
    submitAdjustForm() {
      if(this.adjustWplanSelected.planFinishdate<this.adjustWplanSelected.planStartdate){
        this.$modal.msgError("排产完成时间不能小于排产开始时间");
        return;
      }
      this.adjustopen = false;
    },
    cancel2() {
      this.adjustopen = false;
    },
    reset2(){
      this.form2 = {
        mId: null,
        planStartDate: null,
        planEndDate: null
      };
      this.resetForm("form2");
    },
    load(tree, treeNode, resolve) {
      console.log(tree);
      let data = {
        "parentBomCode": tree.bomCode,
        "productId": tree.productId,
        "orderCode": tree.orderCode,
        "customName": tree.customName,
        "sampleNum": tree.sampleNum ? tree.sampleNum : 0,
        "workerOrdernum": tree.workerOrdernum ? tree.workerOrdernum : 0,
        // "semiProductPlanNum": tree.semiProductPlanNum ? tree.semiProductPlanNum : tree.planNum
      };
      listChildren(data).then((res) => {   //getChildMenu是我们自己的调用后台的封装
        if (res.data && res.data.length === 0) {
          this.$modal.msgError(`${tree.bomCode}|${tree.bomName}, 未加载到子项物料数据`);
        }
        resolve(                            //resolve是组件的
          res.data  //根据自己的格式,将查到的子菜单数组填充
        )
      })
    },

    //打印周计划
    printPlan() {
      if(this.planCal==false){
        alert("请先排产,再打印周计划");
        return;
      }

      this.form1.wplanList=[];
      for(let obj of this.wplanProductVOList) {
        for(let cur of obj.wplanList) {
          this.form1.wplanList.push(cur);
        }
      }

      printPlan(this.form1).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '周排产_工单'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },

    getFactoryList() {
      this.loading = true;
      listFactory({"level":2}).then(response => {
        this.factoryList = response.data;

        this.queryParams.factoryId = this.factoryList[0].deptId;
        this.getTeamList(this.queryParams.factoryId);
        //this.teamList = [];

        this.loading = false;
      });
    },
    factoryChange(){
      this.getTeamList(this.queryParams.factoryId);
    },
    /** 查询订单信息列表 */
    getTeamList(parentId) {
      this.loading = true;
      listTeam({"parentId":parentId}).then(response => {
        this.teamList = response.data || [];
        this.loading = false;
      });
    },

    handlePrint(row) {
      this.loading = true;
      const ids = row.id || this.ids;
      printWplanWorkOrder(ids).then(response => {
        let blob = new Blob([response], { type: "application/vnd.ms-excel" });
        var downloadElement = document.createElement("a");

        var href = window.URL.createObjectURL(blob); //创建下载的链接

        downloadElement.href = href;

        downloadElement.download = '月排产_工单'; //下载后文件名

        document.body.appendChild(downloadElement);

        downloadElement.click(); //点击下载

        document.body.removeChild(downloadElement); //下载完成移除元素

        window.URL.revokeObjectURL(href); //释放掉blob对象

        this.loading = false;
      });
    },
    getThisSaturday() {
      var currentDate = new Date();
      var currentDay = currentDate.getDay(); // 获取当前是星期几（0-6，0代表星期日）
      var daysUntilFriday = 6 - currentDay;
      currentDate.setDate(currentDate.getDate() + daysUntilFriday);
      return this.form.weekStartDate=currentDate;
    },
    getNextSaturday() {
      var currentDate = new Date();
      var currentDay = currentDate.getDay(); // 获取当前是星期几（0-6，0代表星期日）
      var daysUntilFriday = 13 - (currentDay+1);
      currentDate.setDate(currentDate.getDate() + daysUntilFriday);
      return this.form.weekEndDate=currentDate;
    },
    handleDisable(row, index) {
      if (row.wplanStatus == '1') {
        return false
      } else {
        return true
      }
    },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      if (!this.queryParams.plan_months) {
        this.$modal.msgError("请选择排产月份");
        return;
      }
      this.queryParams.plan_month = "";
      if (Array.isArray(this.queryParams.plan_months)) {
        for (let i = 0; i < this.queryParams.plan_months.length; i++) {
          if (i != this.queryParams.plan_months.length - 1) {
            this.queryParams.plan_month += this.queryParams.plan_months[i] + ",";
          } else {
            this.queryParams.plan_month += this.queryParams.plan_months[i];
          }
        }
      } else {
        this.queryParams.plan_month = this.queryParams.plan_months;
      }
      newAdjustList(this.queryParams).then(response => {
        this.newOrderPlanList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch((error) => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        weekStartDate: null,
        weekEndDate: null,
        workOrderIds: null
      };
      this.resetForm("form");
    },
    reset1() {
      this.form1 = {
        wplanList: null
      };
      this.resetForm("form1");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log("多个月", this.queryParams);
      this.queryParams.excludeIds = [];
      this.queryParams.pageNum = 1;
      if(this.queryParams.teamId!=null && this.queryParams.teamId!=undefined){
        this.teamSelect = false;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 执行排产操作 */
    handlePlan(row) {
      this.open = true;
      this.adjustPlan = row;
      this.reset();
      this.reset1();
      this.loading2 = true;
      const ids = row.id;
      this.orderplanList = null;
      this.wplanProductVOList = [];
      doneGroupList({"ids":ids+'',"teamId":row.teamId}).then(response => {
        this.wplanProductVOList = response.data.wplanProductVOList || [];

        this.open = true;
        this.planCal = false;
        this.loading2 = false;

        this.teamName = response.data.teamName;
        this.selectedCount = this.wplanProductVOList.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.nextCapacity);
        this.needCapacity = new Number(response.data.needCapacity);
      });
    },

    excutePlan() {
      if(this.wplanProductVOList.length==0){
        this.$modal.msgError("无排产工单，无法排产计算");
        return;
      }
      let planWorkOrderList = [];
      for(let obj of this.wplanProductVOList) {
        for(let cur of obj.wplanList) {
          planWorkOrderList.push(cur);
        }
      }
      this.loading2 = true;
      this.form.teamId = this.adjustPlan.teamId;
      this.form.workOrderIds = planWorkOrderList.map(item => item.id).join(',')
      adjustNewPlan(this.form).then(response => {
        this.wplanProductVOList = response.data.wplanProductVOList || [];
        this.$modal.msgSuccess("排产计算成功");
        this.teamName = response.data.teamName;
        this.selectedCount = this.wplanProductVOList.length;
        this.standardCapacity = new Number(response.data.standardCapacity);
        this.totalStandardCapacity = new Number(response.data.totalStandardCapacity);
        this.restCapacity = new Number(response.data.nextCapacity);
        this.needCapacity = new Number(response.data.needCapacity);
        this.planCal = true;
        this.loading2 = false;
      });
    },

    handleAdjust(row) {
      this.reset2();
      this.adjustWplanSelected = row;
      this.adjustopen = true;
      this.form2.id = row.id;
      this.form2.workorderId = row.workorderId;
      this.form2.planStartDate = row.planStartDate;
      this.form2.planEndDate = row.planEndDate;
      this.form2.factoryId = row.factoryId;
      this.form2.teamId = row.teamId;
      this.form2.bomCode = row.bomCode;

      // 原来的结束日期
      this.form2.planStartDate1 = row.planStartDate;
      if (!this.form2.planEndDate1) {
        this.form2.planEndDate1 = row.planEndDate;
      }
      console.log("form2表单-调整赋值", this.form2);
    },
    /** 调整排产日期功能 提交按钮 */
    submitForm() {
      this.planCal = false;

      if(this.form2.planEndDate1<this.form2.planEndDate){
        this.$modal.msgError("调整排产时间只能提前");
        return;
      }

      if(this.form2.planEndDate1>this.form2.planEndDate){
        this.form3.id = this.form2.id;
        this.form3.workorderId = this.form2.workorderId;
        this.form3.planStartDate = this.form2.planStartDate1;
        this.form3.planEndDate = this.form2.planEndDate1;
        this.form3.adjustEndDate = this.form2.planEndDate;
        // this.form3.detailList = this.form2.detailList;
        this.form3.factoryId = this.form2.factoryId;
        this.form3.teamId = this.form2.teamId;
        this.form3.bomCode = this.form2.bomCode;
        adjustNewPlan(this.form3).then((response) => {
          // TODO 只调整了这个值
          this.form2.planStartDate = response.data.adjustStartDate;
          this.form2.planEndDate = response.data.adjustEndDate;
          this.form2.isDelay = 1;
          this.planCal = true;
          this.adjustopen = false;
          for(let productItem of this.wplanProductVOList) {
            for(let plan of productItem.wplanList) {
              if (plan.id === this.form2.id) {
                Object.assign(plan, this.form2);
                break;
              }
            }
          }
        }).catch(error => {
        });
      }
    },

    submitPlan() {
      console.log("form2表单-提交调整", this.form2);
      if(this.planCal==false){
        this.$modal.msgError("请先做排产日期调整, 再提交");
        return;
      }
      if (!this.form2.planStartDate) {
        this.$modal.msgError("排产开始日期为空, 请重新选择");
        return;
      }
      // TODO 需要真正去后台调整日期
      const data = {
        workorderId: this.form2.workorderId,
        planStartdate: this.formatDateToYYYYMMDD(this.form2.planStartDate),
        planFinishdate: this.formatDateToYYYYMMDD(this.form2.planEndDate),
      };
      this.$modal.confirm('确认要调整排产日期，提交生效吗?').then(() => {
        submitAdjustNewPlan(data).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.adjustopen = false;
          this.open = false;
          this.getList();
        }).catch((error) => {
        });
      }).then(() => {
      }).catch(() => {
      });
    },

    newplanCancel(row) {
      this.loading = true;
      const that = this;
      this.$modal.confirm(`确认要取消 \n [ ${row.bomCode} - ${row.bomName} ] \n 产品排产吗？`).then(function() {
        newplanCancel({
          "contractCode": row.contractCode,
          "orderCode": row.orderCode,
          "workorderId": row.id,
          "productCode": row.productCode
        }).then(response => {
          that.loading = false;
          that.$modal.msgSuccess("取消成功");
          that.getList();
        }).catch(() => {
          that.loading = false;
        });
      }).then(() => {
      }).catch(() => {
        this.loading = false;
      });
    },
  }
};
</script>
